package com.kintreda.ieco_server.module.qrcode.web;

import com.kintreda.ieco_server.bean.qrcode.QrcodeRecord;
import com.kintreda.ieco_server.bean.qrcode.batch;
import com.kintreda.ieco_server.core.web.BaseController;
import com.kintreda.ieco_server.core.web.R;
import com.kintreda.ieco_server.module.qrcode.service.IBatchService;
import com.kintreda.ieco_server.module.qrcode.service.IQrCodeRecordService;
import com.kintreda.ieco_server.util.Parameters;
import com.kintreda.ieco_server.util.file.FileToZip;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @Created by IntelliJ IDEA
 * @Project_Name ieco_server
 * @Package com.kintreda.ieco_server.module.qrcode.web
 * @Author ZhongYao_H
 * @Date 2019/4/30:10:45
 * @Year 2019 Month 04 Day 30
 * @Date_zh 2019 年 四月 星期二
 */
@Controller
@RequestMapping({"/qrcode","/scan"})
public class QrCodeController extends BaseController {

    @Autowired
    private IBatchService batchService;
    @Autowired
    private IQrCodeRecordService qrCodeRecordService;
    @Value("#{properties['Kqrcode.prefix']}")
    private String prefixK;
    @Value("#{properties['qrcode.prefix']}")
    private String prefix;
    @Value("#{properties['server.domian']}")
    private String doman;
    @Value("#{properties['qrcode.path']}")
    private String resourcsPath;
    @Value("#{properties['scan.qrcode']}")
    private String url;

    /**
     *
     * 扫码
     * @param code
     * @return
     */
    @RequestMapping("/qrcode/ecobag")
    private Object scanCode(String code){
        //TODO 判断袋子是否还有使用中未结算 如果有 则不生成订单
        //TODO 用户确实使用则生成使用订单 @UsageRecord


        return null;
    }


    @RequestMapping("/list")
    public ModelAndView list (){
        return new ModelAndView("code/code-list");
    }

    @RequestMapping(value = "/query",method = RequestMethod.POST)
    @ResponseBody
    public Object query(){
        return qrCodeRecordService.query("from QrcodeRecord ORDER BY createDate  desc",null);
    }

    @RequestMapping("/add")
    public ModelAndView add(){
        return  new ModelAndView("code/code-add");
    }

    @RequestMapping("/kimsvolume")
    public ModelAndView kimsVolume(){
        return  new ModelAndView("code/kcode-add");
    }

    /**
     * 二维码生成规则
     * https://www.xxx.com/scan/qrcode/ecobag?code=EA000001
     *
     * @param batch
     * @param number
     * @return
     */
    @Transactional
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public R generateCode(String batch, int number){
        batch = batch.toUpperCase();
        batch  batDB  = batchService.getBatch(batch);
        Map<String ,Object> result = null;
        if (batDB!=null){
            int numDB = Integer.parseInt(batDB.getNumber());
            result = batchService.generateCodes(doman,url,prefix,batch,number,Integer.parseInt(batDB.getNumber()),true);
            batDB.setNumber((numDB+number)+"");
            batchService.update(batDB);
        }else {
            batch bat = new batch();
            bat.setCode(batch);
            bat.setNumber(number+"");
            result = batchService.generateCodes(doman,url,prefix,batch,number,0,false);
            batchService.save(bat);
        }
        QrcodeRecord qrcodeRecord = new QrcodeRecord();
        qrcodeRecord.setNum(result.get("num").toString());
        qrcodeRecord.setType("1");
        qrcodeRecord.setPath(result.get("pfolder").toString());
        qrcodeRecord.setFolder(result.get("folder").toString());
        qrcodeRecord.setBatch(result.get("batch").toString());
        qrCodeRecordService.save(qrcodeRecord);
        return R.ok("二维码生成成功!");

    }

    /**
     * 二维码生成规则
     * https://www.xxx.com/scan/qrcode/ecobag?code=KA000001
     *
     * @param batch
     * @param number
     * @return
     */
    @Transactional
    @RequestMapping(value = "/kimsvolume",method = RequestMethod.POST)
    @ResponseBody
    public R generateKimsVolume(String batch, int number){

        batch = batch.toUpperCase();
        batch  batDB  = batchService.getBatch(batch);
        Map<String ,Object> result = null;
        if (batDB!=null){
            int numDB = Integer.parseInt(batDB.getNumber());
            result = batchService.generateKimsVolume(doman,url,prefixK,batch,number,Integer.parseInt(batDB.getNumber()),true,Parameters.LOG);
            batDB.setNumber((numDB+number)+"");
            batchService.update(batDB);
        }else {
            batch bat = new batch();
            bat.setCode(batch);
            bat.setNumber(number+"");
            result = batchService.generateKimsVolume(doman,url,prefixK,batch,number,0,false, Parameters.LOG);
            batchService.save(bat);
        }
        QrcodeRecord qrcodeRecord = new QrcodeRecord();
        qrcodeRecord.setNum(result.get("num").toString());
        qrcodeRecord.setType("2");
        qrcodeRecord.setPath(result.get("pfolder").toString());
        qrcodeRecord.setFolder(result.get("folder").toString());
        qrcodeRecord.setBatch(result.get("batch").toString());
        qrCodeRecordService.save(qrcodeRecord);
        return R.ok("代金卷生成成功!");

    }





    /**
     * 下载生成二维码压缩包
     *
     * @param response
     */
    @RequestMapping(value = "/download",method = RequestMethod.POST)
    public void download(String folder, String pfolder, HttpServletResponse response) throws IOException {
        File file = new File(resourcsPath+pfolder+File.separator+folder);
        File zip = null;
        if (file.isDirectory()){
            zip = new File(file+File.separator+folder+".zip");
            if (!zip.exists()){
                FileToZip.fileToZip(file.getPath(),file.getPath(),folder);
                zip = new File(file+File.separator+folder+".zip");
            }
            //================== 写出文件
            ServletOutputStream out = null;
            FileInputStream ips = null;
            getRequest();
            try {
            ips = new FileInputStream(zip);
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            //为文件重新设置名字
            response.addHeader("Content-Disposition",  "attachment; filename="+ URLEncoder.encode("二维码.zip","UTF-8") );
            out = response.getOutputStream();
            //读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = ips.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
                out.flush();
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                    out.close();
                    ips.close();
            }
        }else{
        }
    }



}
